package com.situ.company.employee.servlet;

import java.io.IOException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.situ.company.employee.model.EmployeeModel;
import com.situ.company.employee.service.EmployeeService;
import com.situ.company.util.AuthCodeServlet;
import com.situ.company.util.FmtRequest;
import com.situ.company.util.MD5;
import com.situ.company.util.UploadUtil;

@WebServlet("/employee")
public class EmployeeServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	// 控制层：接收请求  获取参数  封装对象  调用方法（传递数据）  返回结果（页面跳转）
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String action = req.getParameter("action");
		String result = "";
		switch (action) {
		case "reg":
			result = reg(req);
			break;
		case "login":
			result = login(req);
			break;
		case "logout":
			req.getSession().removeAttribute("user");
			resp.sendRedirect(req.getContextPath() + "/web/login.jsp");
			break;
		case "add":
			result = add(req);
			break;
		case "del":
			result = del(req);
			break;
		case "upd":
			result = upd(req);
			break;
		case "updDept":
			result = updDept(req);
			break;
		case "sel":
			result = sel(req);
			break;
		case "get":
			result = get(req);
			break;
		case "list":
			result = list(req);
			break;
		case "resetPass":
			result = resetPass(req);
			break;
		case "updPass":
			result = updPass(req);
			break;
		case "delpic":
			result = delpic(req);
			break;
		default:
			break;
		}
		FmtRequest.out(resp, result);
		
	}
	
	private String delpic(HttpServletRequest req) {
		String code = req.getParameter("code");
		EmployeeModel model = new EmployeeModel(code);
		EmployeeModel mdb = service.selectModel(model);
		String image = mdb.getImage();
		UploadUtil.delFile(image);
		model.setImage("");
		return service.update(model);
	}

	private String updPass(HttpServletRequest req) {
		String code = req.getParameter("code");
		String pass = req.getParameter("pass");
		pass = MD5.encode(pass);
		EmployeeModel model = new EmployeeModel(code, pass);
		return service.update(model);
	}

	private String resetPass(HttpServletRequest req) {
		String code = req.getParameter("code");
		EmployeeModel model = new EmployeeModel(code);
		model.setPass(getDefaultPass());
		return service.update(model);
	}

	private String list(HttpServletRequest req) {
		String code = req.getParameter("code");
		String name = req.getParameter("name");
		String pageIndex = req.getParameter("pageIndex");
		String pageLimit = req.getParameter("pageLimit");
		EmployeeModel model = new EmployeeModel(code,name);
		model.setPageIndex(Integer.parseInt(pageIndex));
		model.setPageLimit(Integer.parseInt(pageLimit));
		model.setPageOn(true);
		List<EmployeeModel> list = service.selectList(model);//1,10
		int count = service.selectCount(model);
		Map<String, Object> map = new HashMap<>();
		map.put("data", list);
		map.put("count", count);
		//分页后的记录条数=带有查询条件的并带有limit的查询结果的记录条数
		//分页前的记录条数=带有查询条件的不带有limit的查询结果的记录条数
		return new JSONObject(map).toString();
	}

	private String get(HttpServletRequest req) {
		String code = req.getParameter("code");
		EmployeeModel model = new EmployeeModel(code);
		EmployeeModel mdb = service.selectModel(model);
		return new JSONObject(mdb).toString();
	}

	private String sel(HttpServletRequest req) {
		String code = req.getParameter("code");
		String name = req.getParameter("name");
		EmployeeModel model = new EmployeeModel(code,name);
		List<EmployeeModel> list = service.selectList(model);
		return new JSONArray(list).toString();
	}

	private String upd(HttpServletRequest req) {
		String code = req.getParameter("code");
		String name = req.getParameter("name");
		EmployeeModel model = new EmployeeModel(code);
		model.setName(name);
		return service.update(model);
	}
	private String updDept(HttpServletRequest req) {
		String code = req.getParameter("code");
		String depCode = req.getParameter("depCode");
		EmployeeModel model = new EmployeeModel(code);
		model.setDepCode(depCode);
		return service.update(model);
	}
	
	private String del(HttpServletRequest req) {
		String code = req.getParameter("code");
		EmployeeModel model = new EmployeeModel(code);
		return service.delete(model);
	}

	private String add(HttpServletRequest req) {
		String code = req.getParameter("code");
		String name = req.getParameter("name");
		String pass = req.getParameter("pass");
		pass = getDefaultPass();//设置默认密码
		EmployeeModel model = new EmployeeModel(code,name,pass);
		return service.insert(model);
	}

	private EmployeeService service = new EmployeeService();

	/**
	 *  登录，返回0=账号不存在。返回1=登陆成功，返回2=密码错误，返回'A'=验证码错误
	 * @param req
	 * @return
	 */
	private String login(HttpServletRequest req) {
		String code = req.getParameter("code");
		System.out.println(code);
		String pass = req.getParameter("pass");
		System.out.println(pass);
		//pass = MD5.encode(pass);
		EmployeeModel model = new EmployeeModel(code, pass);
		
		String authCode = req.getParameter("authcode");
		System.out.println(authCode);	// null
		Object authCodeSession = req.getSession().getAttribute(AuthCodeServlet.name);
		System.out.println(authCodeSession);
		if (!authCodeSession.toString().equals(authCode)) {
			return "A";
		}
		EmployeeModel mdb = service.selectModel(model);
		if (mdb == null) { // 为什么没有pass? where code=? and pass=?
			return "0";
		}
		if (mdb.getPass().equals(model.getPass())) {
			req.getSession().setAttribute("user", mdb);
			return "1";
		}
		return "2";
		//return service.login(model,req);
	}

	private String reg(HttpServletRequest req) {
		String code = req.getParameter("code");
		String name = req.getParameter("name");
		String pass = req.getParameter("pass");
		if (pass == null || pass.trim().isEmpty()) {
			pass = getDefaultPass();//设置默认密码
		}else {
			pass = MD5.encode(pass);
		}
		String authCode = req.getParameter("authcode");
		Object authCodeSession = req.getSession().getAttribute(AuthCodeServlet.name);
		if (!authCodeSession.toString().equals(authCode)) {
			return "A";
		}	
		EmployeeModel model = new EmployeeModel(code, name, pass);
		return service.insert(model);
	}
	
	private String getDefaultPass() {
		return MD5.encode("123456");
	}
}
